import { FC , useEffect, useState } from "react"
import styles from './index.module.scss'
type PropsType = {
    fe_id: string;
    props: {
        title: string;
        list: Array<{
            value: string;
            text: string;
            checked: boolean;
        }>;
        isVertical: boolean;
    }
}
const QuestionCheckbox:FC<PropsType> = ({fe_id, props}) => {
    const {title, list=[], isVertical} = props;

    const [checkedValues, setCheckedValues] = useState<string[]>([]);

    useEffect(()=> {
        list.forEach((item) => {
            if(item.checked){
                setCheckedValues((checkedValues) => checkedValues.concat(item.value))
            }
        })
    },[list]);
    function toggleChecked(value: string){
           
            const index = checkedValues.findIndex((item) => item === value)
            if(index !== -1){
                setCheckedValues(checkedValues.filter((item) => item === value));
            }else{
                setCheckedValues(checkedValues.concat(value));
            }
    }
    return <>
    <p>{title}</p>
    <ul className={styles.list}>
        {list.map((option) => {
            const {value: val, text, checked} = option;
            return <>
            <input type="hidden" name={fe_id} value={checkedValues.join(',')} />
            <li key={val} className={isVertical ? styles['vertical-item'] : styles['horizontal-item']}>
                <label >
                <input type="checkbox" value={val} defaultChecked={checked} onChange={() =>toggleChecked(val)}/>
                {text}
                </label>
                </li>
            </>
            
        })}
    </ul>
    </>
}
export default QuestionCheckbox;